/*******************************************************************************
 * 
 * author : huangyuan email:huangyuan3h@gmail.com
 * 
 * control main1.html
 * 
 * 
 */

// User cookie
var UserCookie = function() {
	if (!UserFactory.checkLogin()) {

		location.href = '../index.html';

	} else {
		$("#userName").html(User.userName);
	}

	$(".loginDiv").find("a").button().click(function() {
		UserFactory.clear();
		location.href = '../index.html';
	});

};

// this function will follow the DialogJSON to create the dialog
var createMenuTitle = function() {
	if (AppData == undefined || AppData == null) {
		alert("sorry loading data error");
	} else {

		$.each(AppData, function(key) {

			var str = "<li  ";

			if (this.metro.hide == "true" || this.metro.hide == true) {
				str += "style='display:none;'";
			}

			str += "><span id=\"" + key + "_menu\" class=\"navlink\" location=\"" + this.metro.location + "\" key=\"" + key + "\" >" + this.metro.title + "</span>" +

			"<div class=\"dropdown\" ><p>" + this.metro.description + "</p></div>" + "</li>";

			$("#nav_taget").append(str);
		});

	}

};

var initnav = function() {

	$('#navigation_horiz').naviDropDown({
		dropDownWidth : '300px'
	});

	$('#navigation_vert').naviDropDown({
		dropDownWidth : '300px',
		orientation : 'vertical'
	});

};

var initialTabs = function() {
	var tabs = $("#tabs").tabs();

	$(".navlink").click(function() {
		
		var t = $(this);
		if ($("#" + t.attr("id") + "_dialog").length == 0) {
			var li = "<li><a href=\"#" + t.attr("id") + "_dialog\" id=\""+ t.attr("id")+"_tab\">" + t.html() + "</a>" + " <span class=\"ui-icon ui-icon-close\" role=\"presentation\" >Remove Tab</span>" + "</li>";
			var div = "	<div id=\"" + t.attr("id") + "_dialog\" class=\"Dialogs\">	<iframe src=\"" + t.attr("location") + "?key=" + t.attr("key") + "\" class=\"Dialog-content\">" + "</iframe></div>";
			tabs.find(".ui-tabs-nav").append(li);
			tabs.find("#tabContent").append(div);
			tabs.tabs("refresh");
			$(".ui-icon-close").click(function() {
				$($(this).parent().find("a").attr("href")).remove();
				$(this).closest("li").remove();
				
			});
			$("#" + t.attr("id") + "_tab").trigger("click");
		}else{
			
			$("#" + t.attr("id") + "_tab").trigger("click");
		}

	});
};

// main function
$(function() {
	UserCookie();

	createMenuTitle();
	initnav();
	initialTabs();
});